
SeuratStackCountPlot <- function(seurat.object,
                                 group.by,
                                 stack.by,
                                 percentage = FALSE,
                                 bar.width = 0.8,
                                 xlab = "",
                                 x.axis.angle = 45,
                                 ylab = "",
                                 title = NULL,
                                 legend.title = NULL,
                                 cols = NULL
                                 
                                 
                                 ) {
  plot.table <- seurat.object@meta.data %>%
    dplyr::count(!! sym(group.by), !! sym(stack.by)) %>%
    dplyr::mutate(value = n)
  if (percentage)
    plot <- plot.table %>%
    ggplot(aes(x = !!sym(group.by), y = value, fill = !!sym(stack.by))) + 
    geom_bar(color = "black", stat = "identity", position = "fill", width = bar.width) +
    scale_y_continuous(labels = scales::percent)
  else 
    plot <- plot.table %>%
    ggplot(aes(x = !!sym(group.by), y = value, fill = !!sym(stack.by))) +
    geom_bar(color = "black", stat = "identity", position = "stack", width = bar.width)
  plot <- plot + 
    cowplot::theme_cowplot() +
    theme(axis.text.x = element_text(angle = x.axis.angle, hjust = 0.5, vjust = 0.5)) +
    xlab(xlab) +
    ylab(ylab)
  if (! is.null(legend.title))
    plot <- plot +
    guides(fill = guide_legend(title = labs(title = legend.title)))
  else
    plot <- plot + guides(fill = guide_legend(title = NULL))
  # theme(axis.ticks.length = unit(0.5, 'cm'))
  if (! is.null(title))
    plot <- plot +
    ggtitle(title) +
    theme(plot.title = element_text(hjust = 0.5))
  if (! is.null(cols))
    plot <- plot +
    scale_fill_manual(values = cols)
  plot
}
